using System;
using System.Windows.Forms;
using Curriculum.DataSet;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using E4RPTools;

namespace Curriculum.Controls
{
    public partial class VacancyXtraForm : XtraForm
    {
        private long _documentId;
        private BackOfficeController _controller;
        private VacancyDataSet _dataSet;

        #region Properties

        public long DocumentId
        {
            set { _documentId = value; }
        }

        public BackOfficeController Controller
        {
            set { _controller = value; }
        }

        #endregion

        public VacancyXtraForm()
        {
            InitializeComponent();
            Load += VacancyXtraFormLoad;
            OKSimpleButton.Click += OKSimpleButtonClick;
            positionLookUpEdit.EditValueChanging += PositionLookUpEditEditValueChanging;
        }

        #region Private Methods

        private void MergeData()
        {
            _dataSet = new VacancyDataSet();
            if (_documentId <= 0)
            {
                var vacancy = _dataSet.Vacancy.NewVacancyRow();
                vacancy.Id = _documentId;
                vacancy.Opennings = 0;
                _dataSet.Vacancy.AddVacancyRow(vacancy);
            }
            else
                _dataSet.Merge(_controller.GetVacancy(_documentId));
        }

        private void SetupPositionLookupData()
        {
            positionDataSet = _controller.GetPositions("");
            positionLookUpEdit.Properties.Columns.Clear();
            positionLookUpEdit.Properties.Columns.AddRange(new[] {
                new LookUpColumnInfo("Id", "Id", 85, FormatType.None, "", false, HorzAlignment.Near),
                new LookUpColumnInfo("Area", "Area", 85, FormatType.None, "", true, HorzAlignment.Near),
                new LookUpColumnInfo("SubArea", "SubArea", 85, FormatType.None, "", true, HorzAlignment.Near),
                new LookUpColumnInfo("Name", "Name", 85, FormatType.None, "", true, HorzAlignment.Near)});
            positionLookUpEdit.Properties.DisplayMember = positionDataSet.Position.NameColumn.ColumnName;
            positionLookUpEdit.Properties.ValueMember = positionDataSet.Position.IdColumn.ColumnName;            
            positionLookUpEdit.Properties.DataSource = positionDataSet.Position;
            positionLookUpEdit.Properties.BestFit();
        }

        private void SetDataToControls()
        {
            areaTextEdit.Text = _dataSet.Vacancy[0].IsAreaNull() ? "" : _dataSet.Vacancy[0].Area;
            subAreaTextEdit.Text = _dataSet.Vacancy[0].IsSubAreaNull() ? "" : _dataSet.Vacancy[0].SubArea;
            positionLookUpEdit.Text = _dataSet.Vacancy[0].IsPositionNull() ? "" : _dataSet.Vacancy[0].Position;            
            referenceTextEdit.Text = _dataSet.Vacancy[0].IsReferenceNull() ? "" : _dataSet.Vacancy[0].Reference;
            if (!_dataSet.Vacancy[0].IsStartNull()) startDateEdit.EditValue = _dataSet.Vacancy[0].Start;
            descriptionTextEdit.Text = _dataSet.Vacancy[0].IsDescriptionNull() ? "" : _dataSet.Vacancy[0].Description;
            if(!_dataSet.Vacancy[0].IsAcceptingStartNull()) acceptingStartDateEdit.EditValue = _dataSet.Vacancy[0].AcceptingStart;
            if (!_dataSet.Vacancy[0].IsAcceptingEndNull()) acceptingEndDateEdit.EditValue = _dataSet.Vacancy[0].AcceptingEnd;
            openningsSpinEdit.EditValue = _dataSet.Vacancy[0].Opennings;
        }

        private void GetDataFromControls()
        {
            _dataSet.Vacancy[0].Area = areaTextEdit.Text;
            _dataSet.Vacancy[0].SubArea = subAreaTextEdit.Text;

            if (positionLookUpEdit.EditValue == Convert.DBNull)
                _dataSet.Vacancy[0].SetPositionNull();
            else
                _dataSet.Vacancy[0].Position = positionLookUpEdit.Text;            
            _dataSet.Vacancy[0].Reference = referenceTextEdit.Text;
            if (startDateEdit.EditValue == Convert.DBNull)
                _dataSet.Vacancy[0].SetStartNull();
            else
                _dataSet.Vacancy[0].Start = Convert.ToDateTime(startDateEdit.EditValue);
            _dataSet.Vacancy[0].Description = descriptionTextEdit.Text;
            if (acceptingStartDateEdit.EditValue == Convert.DBNull)
                _dataSet.Vacancy[0].SetAcceptingStartNull();
            else
                _dataSet.Vacancy[0].AcceptingStart = Convert.ToDateTime(acceptingStartDateEdit.EditValue);
            if (acceptingEndDateEdit.EditValue == Convert.DBNull)
                _dataSet.Vacancy[0].SetAcceptingEndNull();
            else
                _dataSet.Vacancy[0].AcceptingEnd = Convert.ToDateTime(acceptingEndDateEdit.EditValue);
            _dataSet.Vacancy[0].Opennings = Convert.ToInt64(openningsSpinEdit.EditValue);
        }

        private void ClearControlErrors()
        {
            dxErrorProvider.SetError(areaTextEdit, "");
            dxErrorProvider.SetError(subAreaTextEdit, "");
            dxErrorProvider.SetError(positionLookUpEdit, "");
            dxErrorProvider.SetError(referenceTextEdit, "");
            dxErrorProvider.SetError(startDateEdit, "");
            dxErrorProvider.SetError(descriptionTextEdit, "");
            dxErrorProvider.SetError(acceptingStartDateEdit, "");
            dxErrorProvider.SetError(acceptingEndDateEdit, "");
            dxErrorProvider.SetError(openningsSpinEdit, "");
        }

        private Control GetControl(string reference)
        {
            switch (reference)
            {
                case "Area":
                    return areaTextEdit;
                case "SubArea":
                    return subAreaTextEdit;
                case "Position":
                    return positionLookUpEdit;
                case "Reference":
                    return referenceTextEdit;
                case "Start":
                    return startDateEdit;
                case "Description":
                    return descriptionTextEdit;
                case "AcceptingStart":
                    return acceptingStartDateEdit;
                case "AcceptingEnd":
                    return acceptingEndDateEdit;
                case "Opennings":
                    return openningsSpinEdit;
                default:
                    return null;
            }
        }

        private void SetControlErrors(Result result)
        {
            foreach (var error in result.Errors)
                dxErrorProvider.SetError(GetControl(error.Reference), error.Message);
        }

        #endregion

        void VacancyXtraFormLoad(object sender, EventArgs e)
        {
            MergeData();
            SetupPositionLookupData();
            SetDataToControls();
        }

        void PositionLookUpEditEditValueChanging(object sender, ChangingEventArgs e)
        {
            if(e.NewValue == null)
            {
                areaTextEdit.Text = "";
                subAreaTextEdit.Text = "";
            }
            else
            {
                var position = positionDataSet.Position.FindById(Convert.ToInt64(e.NewValue));
                areaTextEdit.Text = position.Area;
                subAreaTextEdit.Text = position.SubArea;
            }
        }

        void OKSimpleButtonClick(object sender, EventArgs e)
        {
            ClearControlErrors();
            GetDataFromControls();
            var result = _controller.IsVacancyValid(_dataSet);
            if (result.Failed)
            {
                DialogResult = DialogResult.None;
                SetControlErrors(result);
            }
            else
                _controller.SaveVacancy(_dataSet);
        }
    }
}